import Vue from 'vue'
import Vuex from 'vuex'
import {
    userInfoAPI
} from '@/api'


import {
    saveToken,
    getToken,
    delToken
} from '@/utils/auth'

Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
        tokenObj: getToken() || {},
        userInfo: {}
    },
    mutations: {
        changeToken(state, obj) {
            state.tokenObj = obj
            saveToken(obj)
        },
        changeUserInfo(state, obj) {
            state.userInfo = obj
        },
        logout(state) {
            state.tokenObj = {};
            state.userInfo = {};
            delToken()
        }
    },
    actions: {
        async getUserInfo(context) {
            // 发请求
            if (!context.state.userInfo.name) {
                // 请求登录的用户信息
                let res = await userInfoAPI();
                // 请求到了后就把数据存到vuex里
                context.commit("changeUserInfo", res.data.data);
            }
        }
    }
})
export default store